<?php

namespace app\controller;

use app\BaseController;
use app\model\Archives;
use app\model\Character;
use app\model\Collection;
use app\model\Contract;
use app\model\Img;
use app\model\Parameter;
use app\model\Product;
use app\model\User_character;

/**
 * 业务合同
 * Class Contract
 * @package app\controller
 * @author 下雨吧จุ๊บ
 */
class ContractController extends BaseController
{
    /**
     * @apiGroup 业务合同
     * @apiVersion 1.0.0
     * @api {GET} /contract  业务合同列表
     * @apiDescription 业务合同列表
     * @apiParam {String} archivesid 客户档案id(选填 1:填写,客户档案按钮;2:不填写:左侧导航接口)
     * @apiParam {String} listRows 每页数量(必填*)
     * @apiParam {String} page 当前页数(必填*)
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * data: 业务合同列表,
     * message: '获取业务合同列表成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function index()
    {
        $data = input();
        if (empty($data['listRows'])) {
            $data['listRows'] = '8';
        }
        if (empty($data['page'])) {
            $data['page'] = '1';
        }
        $map[] = ['co.title','like','%%'];
        if (!empty($data['map']['title'])){
            $map[] = ['co.title','like','%'. $data['map']['title'] .'%'];
        }
        if (empty($data['archivesid'])){
            //左侧菜单业务合同按钮
            $data['list'] = Contract::alias('co')
//                ->join(['character' => 'c'], 'c.id=co.characterid')
                ->join(['parameter' => 'p'], 'p.id=co.paytypeid')
                ->join(['parameter' => 'p1'], 'p1.id=co.contracttypeid')
                ->join(['user' => 'u'], 'u.id=co.userid')
                ->join(['user' => 'u1'], 'u1.id=co.serviceid')
                ->where($map)
                ->field('co.*,u.realname as name,u1.realname as servicename,p.title as paytypetitle,p1.title as contracttypetitle')
                ->paginate([
                    'list_rows' => $data['listRows'],
                    'page' => $data['page'],
                ]);
        }else{
            //客户档案中回访按钮
            $data['list'] = Contract::alias('co')
//                ->join(['character' => 'c'], 'c.id=co.characterid')
                ->join(['parameter' => 'p'], 'p.id=co.paytypeid')
                ->join(['parameter' => 'p1'], 'p1.id=co.contracttypeid')
                ->join(['user' => 'u'], 'u.id=co.userid')
                ->join(['user' => 'u1'], 'u1.id=co.serviceid')
                ->where('archivesid',$data['archivesid'])
                ->field('co.*,u.realname as name,u1.realname as servicename,p.title as paytypetitle,p1.title as contracttypetitle')
                ->paginate([
                    'list_rows' => $data['listRows'],
                    'page' => $data['page'],
                ]);
        }
        //计算收款金额
        if (!empty($data['list'])){
            foreach ($data['list'] as $k=>$v){
                $data['list'][$k]['alreadyprice'] = Collection::where('contractid',$v['id'])->sum('collectionprice');
            }
        }
        success($data, '获取业务合同列表成功');
    }

    /**
     * @apiGroup 业务合同
     * @apiVersion 1.0.0
     * @api {GET} /contract/create  新增
     * @apiDescription 新增界面
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * data: 跟进阶段列表,
     * message: '获取数据成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function create()
    {
        //部门列表
        $data['character'] = Character::where('status', 1)->select();
        //客户档案列表
        $data['archives'] = Archives::select();
        //获取支付方式列表
        $data['paytype'] = Parameter::where('status', 1)->where('pid', 82)->select();
        //获取合同类型列表
        $data['contracttype'] = Parameter::where('status', 1)->where('pid', 78)->select();
        //获取签订人员/客服人员列表
        $data['user'] = \app\model\User::where('status', 1)->select();
        success($data, '获取数据成功');
    }

    /**
     * @apiGroup 业务合同
     * @apiVersion 1.0.0
     * @api {POST} /contract  新增保存
     * @apiDescription 新增保存
     * @apiParam {String} archivesid 客户档案id
     * @apiParam {String} title 合同名称(必填*)
     * @apiParam {String} customer 客户名称(必填*)
     * @apiParam {String} contractprice 合同金额(必填*)
     * @apiParam {String} saleprice 销售金额(必填*)
     * @apiParam {String} userid 签订人员id(必填*)
     * @apiParam {String} serviceid 客服人员id(必填*)
     * @apiParam {String} contractstarttime 合同开始时间(必填*)
     * @apiParam {String} contractendtime 合同到期时间(必填*)
     * @apiParam {String} serviceendtime 服务到期时间(必填*)
     * @apiParam {String} successtime 签订时间(必填*)
     * @apiParam {String} paycount 付款次数(必填*)
     * @apiParam {String} paytypeid 支付方式id(必填*)
     * @apiParam {String} contracttypeid 合同类型id(必填*)
     * @apiParam {String} content 合同条款
     * @apiParam {String} message 备注
     * @apiParam {String} status 状态
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * message: '新增成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function save()
    {
        $data = input();
        //必填项验证
        if (empty($data['archivesid'])) {
            error('请选择客户');
        }
        //必填项验证
        if (empty($data['title'])) {
            error('请输入合同名称');
        }
        //必填项验证
        if (empty($data['userid'])) {
            error('请选择签订人员');
        }
        //必填项验证
        if (empty($data['serviceid'])) {
            error('请选择客服人员');
        }
        //必填项验证
        if (empty($data['paytypeid'])) {
            error('请选择支付方式');
        }
        //必填项验证
        if (empty($data['saleprice'])) {
            $data['saleprice'] = 0;
        }
        //文件上传操作
        if (!empty($data['file'])){
            $file = $data['file'];
        }
        unset($data['file']);
        //补充时间
        $data['createtime'] = time();
        $data['updatetime'] = time();
        //补充部门id
        $data['characterid'] = User_character::where('userid',$data['userid'])->find()['characterid'];
        //获取最后一位id
        $lastid = Contract::order('id desc')->field('id')->find()['id'];
        //合同编号
        $data['code'] = ordercode($lastid + 1);
        //添加数据
        $result = Contract::insertGetId($data);
        if ($result) {
            //文件操作
            if (!empty($file)){
                $this->file($file,$result);
            }
            success(array(), '新增成功');
        }
        error('新增失败');
    }

    /**
     * @apiGroup 业务合同
     * @apiVersion 1.0.0
     * @api {GET} /contract/:id  编辑读取
     * @apiDescription 编辑页面(:id是指当前id,直接写在路由中)
     * @apiParam {String} id id
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * data: array
     * message: '获取数据成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function read()
    {
        $data = input();
        //必填项验证
        if (empty($data['id'])) {
            error('520数据错误(Missing parameter id)');
        }
        //部门列表
        $data['character'] = Character::where('status', 1)->select();
        //客户档案列表
        $data['archives'] = Archives::select();
        //获取支付方式列表
        $data['paytype'] = Parameter::where('status', 1)->where('pid', 82)->select();
        //获取合同类型列表
        $data['contracttype'] = Parameter::where('status', 1)->where('pid', 78)->select();
        //获取签订人员/客服人员列表
        $data['user'] = \app\model\User::where('status', 1)->select();
        //返回数据详情
        $data['info'] = Contract::where('id', $data['id'])->find();
        success($data, '获取数据成功');
    }

    /**
     * @apiGroup 业务合同
     * @apiVersion 1.0.0
     * @api {PUT} /contract/:id  编辑保存
     * @apiDescription 编辑页面保存(:id是指当前id,直接写在路由中)
     * @apiParam {String} title 合同名称(必填*)
     * @apiParam {String} customer 客户名称(必填*)
     * @apiParam {String} contractprice 合同金额(必填*)
     * @apiParam {String} saleprice 销售金额(必填*)
     * @apiParam {String} userid 签订人员id(必填*)
     * @apiParam {String} serviceid 客服人员id(必填*)
     * @apiParam {String} contractstarttime 合同开始时间(必填*)
     * @apiParam {String} contractendtime 合同到期时间(必填*)
     * @apiParam {String} serviceendtime 服务到期时间(必填*)
     * @apiParam {String} successtime 签订时间(必填*)
     * @apiParam {String} paycount 付款次数(必填*)
     * @apiParam {String} paytypeid 支付方式id(必填*)
     * @apiParam {String} contracttypeid 合同类型id(必填*)
     * @apiParam {String} content 合同条款
     * @apiParam {String} message 备注
     * @apiParam {String} status 状态
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * message: '保存成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function update()
    {
        $data = input();
        //必填项验证
        if (empty($data['archivesid'])) {
            error('请选择客户');
        }
        //必填项验证
        if (empty($data['title'])) {
            error('请输入合同名称');
        }
        //必填项验证
        if (empty($data['userid'])) {
            error('请选择签订人员');
        }
        //必填项验证
        if (empty($data['serviceid'])) {
            error('请选择客服人员');
        }
        //必填项验证
        if (empty($data['paytypeid'])) {
            error('请选择支付方式');
        }
        //必填项验证
        if (empty($data['saleprice'])) {
            $data['saleprice'] = 0;
        }
        //文件上传操作
        if (!empty($data['file'])){
            $this->file($data['file'],$data['id']);
        }
        unset($data['file']);
        //补充部门id
        $data['characterid'] = User_character::where('userid',$data['userid'])->find()['characterid'];
        //更新修改时间
        $data['updatetime'] = time();
        //计算订单金额
        $data['contractprice'] = Product::where('archivesid',$data['id'])->where('channel','contract')->sum('countprice');
        //更新数据
        $result = Contract::where('id', $data['id'])->save($data);
        success(array(), '保存成功');
    }

    /**
     * @apiGroup 业务合同
     * @apiVersion 1.0.0
     * @api {DELETE} /contract/0  删除
     * @apiDescription 删除(路由中直接写0,ids集合使用参数传递)
     * @apiParam {array} ids id集合
     * @apiSuccessExample SuccessExample 成功事例
     * HTTP/1.0.0 200
     * {
     * status: 1,
     * message: '删除成功'
     * }
     * @apiErrorExample ErrorExample 失败选项
     * HTTP/1.0.0 500
     * {
     * status: '0',
     * message: '错误提示'
     * }
     */
    public function delete()
    {
        $data = input();
        //必填项验证
        if (empty($data['ids'])) {
            error('520数据错误(Missing parameter id)');
        }
        $result = Contract::whereIn('id', $data['ids'])->delete();
        success(array(), '删除成功');
    }

    /*
     * 文件上传
     */
    public function file($file,$pid)
    {
        //删除原先的关联
        $result = Img::where('pid',$pid)->delete();
        //重新添加
        $add = array();
        foreach ($file as $k=>$v){
            $add[$k]['table'] = 'contract';
            $add[$k]['pid'] = $pid;
            $add[$k]['url'] = $v;
        }
        $result = Img::insertAll($add);
    }
}
